//获取应用实例
import Toast from "../../assets/ui/toast/toast";
// import Dialog from "../../assets/ui/dialog/dialog";
// const util = require('../../assets/util.js');

const app = getApp();
var socketTask;
Page({
    data: {
        active: 0,
        list: [],
        ready:"",
        meetingNameShow: false,
        dialogType: 'rename',
        meetingName: '',
        handleId: 0,
        handleIndex: 0,
        searchShow: true,
        searchValue: ''
    },
    onLoad() {
        let login = wx.getStorageSync('login') || false;
        if (!login) {
            wx.redirectTo({
                url: `/pages/login/login`
            });
            return
        }
        this.getList()
    },
    onHide() {

        console.log('index onHide');
        socketTask.close(function (close) {
            console.log('关闭 WebSocket 连接。', close)
        })

    },
    onUnload() {
        console.log('index onUnload');
        // wx.closeSocket(function (res) {
        //   console.log('index websocket closeSocket.');
        // });
    },
    onReady() {
        let that = this;
        socketTask = wx.connectSocket({
            url: 'wss://ai.iweigame.com/websocket'
            // url: 'ws://192.168.1.5:8888/websocket'
        });
        socketTask.onOpen(res => {

            console.log('监听 WebSocket 连接打开事件。', res)
        });
        socketTask.onClose(onClose => {
            console.log('监听 WebSocket 连接关闭事件。', onClose)


        });
        socketTask.onError(onError => {
            console.log('监听 WebSocket 错误。错误信息', onError)
        });
        socketTask.onMessage(msg => {
            let that = this;
            if (msg.data === "ok") {
                that.setData({
                    ready: "会议魔盒准备好了，请开始会议吧"

                })
            }
            console.log('监听 WebSocket index received msg:', msg);

        });

        wx.onSocketOpen(function (res) {
            console.log('websocket opened.');
        });
        wx.onSocketError(function (res) {
            console.log('websocket fail');
        });

    },
    getList() {
        wx.showLoading({
            title: `加载中...`,
        });
        let that = this;
        wx.request({
            url: 'https://ai.iweigame.com/aiaudio/getmettinglist',
            data: {},
            success(res) {
                let list = res.data || [];
                list.forEach(item => {
                    item['star'] = false;
                });
                app.globalData.meetingList = list;
                that.setData({
                    list
                })
            },
            fail() {
                Toast.fail('获取失败');
            },
            complete() {
                wx.hideLoading()
            }
        })
    },
    viewRecord(e) {
        // console.log(e.currentTarget.dataset.id);
        wx.navigateTo({
            url: '/pages/detail/detail?id=' + e.currentTarget.dataset.id
        })
    },
    SearchInput(e) {
        this.SearchInstance(e.detail)
    },
    SearchInstance(value) {
        let list = app.globalData.meetingList, filter = [];
        if (value === '') {
            filter = list
        } else {
            filter = list.filter(item => item.meetingname.indexOf(value) !== -1);
        }
        this.setData({
            list: filter
        })
    },
    Search(e) {
        let value = e.detail;
        if (value === '') {
            wx.showToast({
                title: '输入值不能为空',
                icon: 'none'
            })
        }
        this.SearchInstance(value)
    },
    onClose(e) {
        // console.log(e);
        const {position, instance} = e.detail;
        switch (position) {
            case 'left':
            case 'cell':
            case 'right':
                instance.close();
                break;
        }
    },
    collection(e) {
        let that = this,
            dataset = e.currentTarget.dataset;
        let list = this.data.list;
        if (list[dataset.index].star) {// 已收藏
            list[dataset.index].star = false;
            wx.showToast({
                title: '取消收藏',
                icon: 'none'
            })
        }else {
            list[dataset.index].star = true;
            wx.showToast({
                title: '收藏成功',
                icon: 'success'
            })
        }
        app.globalData.meetingList = list;
        this.setData({
            list
        })
    },
    addMeeting() {
        console.log('添加会议');
        this.setData({
            meetingName: '',
            dialogType: 'add',
            meetingNameShow: true
        });

    },
    addMeetingInstance() {
        wx.showLoading({
            title: `添加中...`,
        });
        let meetingName = this.data.meetingName.replace(/\s+/g, ""),
            that = this;
        wx.request({
            url: 'https://ai.iweigame.com/aiaudio/addmetting',
            data: {
                meetingname: meetingName
            },
            success(res) {
                console.log(res.data);
                Toast.success('添加成功');
                that.getList()
            },
            fail() {
                Toast.fail('添加失败');
            },
            complete() {
                that.setData({
                    meetingNameShow: false
                });
                wx.hideLoading()
            }
        })
    },
    rename(e) {
        let that = this,
            dataset = e.currentTarget.dataset;
        this.setData({
            meetingName: '',
            dialogType: 'rename',
            meetingNameShow: true,
            handleId: dataset.id,
            handleIndex: dataset.index
        });
    },
    inputMeetingName(e) {
        this.setData({
            meetingName: e.detail
        })
    },
    confirmRename() {
        let meetingName = this.data.meetingName.replace(/\s+/g, "");
        if (meetingName === '') {
            Toast('会议名称不能为空');
            this.setData({
                meetingNameShow: false
            });
            return;
        }
        if (this.data.dialogType === 'rename') {
            this.renameInstance()
        } else {
            this.addMeetingInstance()
        }
    },
    renameInstance() {
        wx.showLoading({
            title: `重命名中...`,
        });
        let meetingName = this.data.meetingName.replace(/\s+/g, "");
        let that = this;
        wx.request({
            url: 'https://ai.iweigame.com/aiaudio/editmetting',
            data: {
                meetingname: meetingName,
                meetingid: that.data.handleId
            },
            success(res) {
                console.log(res);
                Toast.success('重命名成功');
                let list = that.data.list;
                list[that.data.handleIndex].meetingname = meetingName;
                app.globalData.meetingList = list;
                that.setData({list})
            },
            fail() {
                Toast.fail('操作失败');
            },
            complete() {
                that.setData({
                    meetingNameShow: false
                });
                wx.hideLoading()
            }
        })
    },
    cancelRename() {
        this.setData({
            meetingNameShow: false
        })
    },
    del(e) {
        let that = this,
            dataset = e.currentTarget.dataset;
        // console.log(e.currentTarget.dataset.index);
        wx.showModal({
            title: '警告',
            content: '确定删除？',
            success(res) {
                if (res.confirm) {
                    let list = that.data.list;
                    list.splice(dataset.index, 1);
                    that.delInstance(dataset.id);
                    that.setData({
                        list
                    });
                    app.globalData.meetingList = list;
                    // console.log('删除 - id :' + dataset.id)
                } else if (res.cancel) {
                    console.log('取消')
                }
            }
        })
    },
    delInstance(meetingid) {
        wx.showLoading({
            title: `删除中...`,
        });
        wx.request({
            url: 'https://ai.iweigame.com/aiaudio/delmetting',
            data: {
                meetingid
            },
            success(res) {
                console.log(res.data);
                Toast.success('删除成功');
            },
            fail() {
                Toast.fail('删除失败');
            },
            complete() {
                wx.hideLoading()
            }
        })
    },
    tabbarChange(event) {
        // console.log(event.detail);
        if (event.detail === 1) {
            wx.redirectTo({
                url: '/pages/mine/mine'
            })
        }
    },
    onShareAppMessage() {
        return {
            path: '/pages/index/index'
        }
    }
});
